package com.ayg.test.apitest.core;

import com.ayg.test.apitest.entity.TestCase;
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.Test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

public class AllureReporterListener implements IHookable {
    @Override
    public void run(IHookCallBack iHookCallBack, ITestResult iTestResult) {
        //动态修改Allure的注解
        Method apiTestMethod = null;
        try {
            Method[] method  = ApiEngine.class.getMethods();
            apiTestMethod = ApiEngine.class.getMethod("apiTest",TestCase.class);
        } catch (NoSuchMethodException e) {
            throw  new RuntimeException("找不到方法:apiTest");
        }
        Test testAnnotation = apiTestMethod.getAnnotation(Test.class);
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(testAnnotation);
        Field f = null;
        try {
            f = invocationHandler.getClass().getDeclaredField("memberValues");
            f.setAccessible(true);
            // 获取实例的属性map
            Map<String, Object> memberValues = (Map<String, Object>) f.get(invocationHandler);
            // 修改属性值
            Object[] methodParams = iHookCallBack.getParameters();
            TestCase testCaseObj = (TestCase) methodParams[0];
            System.out.println(testCaseObj.getName());
            memberValues.put("invocationCount", "10");
        } catch (Exception e) {
            throw new RuntimeException("获取Annotation 失败");
        }
        iHookCallBack.runTestMethod(iTestResult);
    }
}
